package edu.csu.smartpark.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class CommonUtil {
    public static Date getCurrentTime()  {
        try {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String now = sdf.format(date);
            Date time  = sdf.parse(now);
            return time;
        } catch (ParseException e){
            log.error("[getCurrentTime] parse time fail");
        }
       return null;
    }

    /*
    * @Description: 生成四位的随机数
    * @Author: LZY
    * @Date: 2021/5/10 20:42
    */
    public static String generateRandom() {
        String num = String.valueOf((int)(Math.random()*Math.pow(10, 4)));
        return num;
    }

    /*
    * @Description: 获取当天日期
    * @Author: LZY
    * @Date: 2021/5/19 17:13
    */
    public static Date getTodayDate(){
        try {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String now = sdf.format(date);
            Date time  = sdf.parse(now);
            return time;
        } catch (ParseException e){
            log.error("[getTodayDate] parse time fail");
        }
        return null;
    }

    /*
    * @Description: URL参数解析
    * @Author: LZY
    * @Date: 2021/6/24 17:56
    */
    public static Map<String, String> URLAnalysis(String url) {
       Map<String, String> paramMap = new HashMap<String, String>();
       String[] parameters = url.substring(url.indexOf('?')+1).split("&");
        for (String param : parameters) {
            String values[] = param.split("=");
            paramMap.put(values[0], values[1]);
        }
        return paramMap;
    }

    /*
    * @Description: 使用MD5算法对raw字符串进行加密
    * @Author: LZY
    * @Date: 2021/6/29 18:11
    */
    public static String EncryptByMD5(String raw) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String encrypt = base64Encoder.encode(messageDigest.digest(raw.getBytes("utf-8")));
            return encrypt;
        }catch (Exception e){
            log.error("[EncryptByMD5] MD5 Encrypt fail");
            return "";
        }
    }

    public static String TimeStampToDate(Long timeStamp, String format){
        if (StringUtil.isEmpty(format))
            format = "yyyy-MM-dd HH:mm:ss";
        return new SimpleDateFormat(format).format(new Date(timeStamp));
    }

}
